import {Button, Drawer, FormInstance, Image, message} from 'antd';
import React, {useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import type {ActionType, ProColumns} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormDependency,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormTreeSelect,
} from '@ant-design/pro-form';
import ProDescriptions, {ProDescriptionsItemProps} from '@ant-design/pro-descriptions';
import {checkTrouble, getTrouble, loadCheckTrouble, rejectTrouble} from './service';
import type {TroubleListItem, TroubleListPagination} from './data';
import {loadOrgSelect} from '@/pages/Enterprise/Org/service';
import {loadPostSelect} from '@/pages/Enterprise/Post/service';
import {loadEmployeeSelect} from '@/pages/Employee/List/service';
import CheckModule from "@/components/CheckModule";

/**
 * 新增或更新隐患信息
 *
 * @param fields
 */

const handleAdd = async (fields: TroubleListItem, mode: boolean) => {
  const hide = message.loading('正在审核');
  try {
    await checkTrouble({...fields});
    hide();
    message.success('审核成功');
    return true;
  } catch (error) {
    // hide();
    // message.error(mode ? '保存失败请重试' : '添加失败请重试');
    return false;
  }
};
/**
 * 新增或更新风险信息
 *
 * @param fields
 */
const handleReject = async (fields: TroubleListItem) => {
  const hide = message.loading('正在拒绝');
  try {
    await rejectTrouble({...fields});
    hide();
    message.success('成功拒绝');
    return true;
  } catch (error) {
    // hide();
    // message.error(mode ? '保存失败请重试' : '添加失败请重试');
    return false;
  }
};
const sourceTypeData = {
  1: {
    text: '人的不安全行为',
  },
  2: {
    text: '物的不安全状态',
  },
  3: {
    text: '不良环境',
  },
  4: {
    text: '管理缺陷',
  },
};
const proposalData = {
  立即整改: '立即整改',
  限时整改: '限时整改',
  停业整改: '停业整改',
};
const troubleLevelData = {
  2: {
    text: '一般',
    color: '#E1E13A',
  },
  4: {
    text: '重大',
    color: '#FF0000',
  },
};
const frequencyData = {
  1: {
    text: '每日一次',
  },
  2: {
    text: '每周一次',
  },
  3: {
    text: '每月一次',
  },
  4: {
    text: '每季度一次',
  },
  5: {
    text: '每年一次',
  },
  6: {
    text: '每半年一次',
  },
  0: {
    text: '仅一次',
  },
};
const requestOrg = async () => {
  return loadOrgSelect({status: '0'}).then(({data}) => {
    return data;
  });
};
const requestPost = async () => {
  return loadPostSelect().then(({data}) => {
    return data;
  });
};

const requestEmployee = async (param: any) => {
  return loadEmployeeSelect(param).then(({data}) => {
    return data;
  });
};

const TroublePage: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [currentRow, setCurrentRow] = useState<TroubleListItem>();
  const columns: ProColumns<TroubleListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
              (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '作业位置场所',
      dataIndex: 'place',
    },
    {
      title: '上报图片',
      dataIndex: 'upload',
      hideInSearch: true,
      hideInTable: true,
      render: (_, record) => <Image width={200} src={record.upload.image}
      />,
    },
    {
      title: '隐患源分类',
      dataIndex: 'sourceType',
      hideInSearch: true,
      valueEnum: sourceTypeData,
    },
    {
      title: '隐患内容',
      dataIndex: 'source',
      render: (_, record) => <span style={{whiteSpace: 'pre-wrap'}}>{record?.source}</span>,
    },
    {
      title: '整改措施',
      hideInSearch: true,
      dataIndex: 'measure',
      render: (_, record) => <span style={{whiteSpace: 'pre-wrap'}}>{record?.measure}</span>,
    },
    {
      title: '排查频次',
      dataIndex: 'frequency',
      hideInSearch: true,
      valueEnum: frequencyData,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: false,
      initialValue: '0',
      valueEnum: {
        '-1': {
          text: '审核通过',
          status: 'Success',
        },
        '0': {
          text: '待审核',
          status: 'Default',
        },
        '-2': {
          text: '审核失败',
          status: 'Error',
        },
      },
    },
    {
      title: '来源',
      dataIndex: 'createMode',
      hideInForm: false,
      search: false,
      initialValue: '2',
      valueEnum: {
        0: {
          text: '创建',
        },
        1: {
          text: '转化',
        },
        2: {
          text: '上报',
        },
        9: {
          text: '导入',
        },
      },
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      search: false,
      defaultSortOrder: 'descend',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,

      render: (_, record) => [
        <a
          key="view"
          onClick={() => {
            setCurrentRow(record);
            setShowDetail(true);
          }}
        >
          查看
        </a>,
        <a
          key="edit"
          onClick={() => {
            formRef.current?.resetFields();
            setCurrentRow(record);
            setEditMode(true);
            setCheckMode(true);
            handleModalVisible(true);
          }}
        >
          审核
        </a>,
      ],
    },
  ];
  const [editMode, setEditMode] = useState<boolean>(false);
  const [checkMode, setCheckMode] = useState<boolean>(false);
  let troubleColor = {'4': '#FF0000', '3': '#FFA500', '2': '#E1E13A', '1': '#0000FF'};

  return (
    <CheckModule code={'SC'}>
      <PageContainer waterMarkProps={{content: ''}}>
        <ProTable<TroubleListItem, TroubleListPagination>
          headerTitle="隐患列表"
          actionRef={actionRef}
          rowKey="troubleId"
          search={{
            labelWidth: 120,
          }}
          request={loadCheckTrouble}
          columns={columns}
          params={{createMode: '2'}}
        />

        <ModalForm<TroubleListItem>
          // title={currentRow?.troubleId || 0 > 0 ? '编辑隐患' : '新建隐患'}
          title={'审核隐患'}
          // width="600px"
          modalProps={{destroyOnClose: true, maskClosable: false}}
          layout={'horizontal'}
          labelCol={{span: 5}}
          wrapperCol={{pull: 1, offset: 1, span: 17}}
          formRef={formRef}
          // size={"large"}
          visible={createModalVisible}
          submitter={{
            submitButtonProps: {
              style: {
                display: 'none',
              },
            },
            render: (props, defaultDoms) => {
              return [
                ...defaultDoms,
                <Button
                  danger
                  key="reject"
                  onClick={async () => {
                    // @ts-ignore
                    const success = await handleReject(formRef.current?.getFieldsFormatValue?.());
                    if (success) {
                      setCurrentRow(undefined);
                      handleModalVisible(false);
                      if (actionRef.current) {
                        actionRef.current.reload();
                      }
                    }
                  }}
                >
                  拒绝
                </Button>,
                <Button
                  type="primary"
                  key="check"
                  onClick={() => {
                    props.submit();
                  }}
                >
                  通过
                </Button>,
              ];
            },
          }}
          onValuesChange={(f, v) => {
            if (f.hasOwnProperty('orgId') || f.hasOwnProperty('postId')) {
              formRef.current?.setFieldsValue({employeeId: undefined});
            }
          }}
          onVisibleChange={(visible) => {
            if (!visible) {
              setCurrentRow(undefined);
            }
            handleModalVisible(visible);
          }}
          onFinish={async (value) => {
            const success = await handleAdd(value, editMode);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          request={(params) => {
            if (params.troubleId > 0) {
              return getTrouble(params).then(({data}) => {
                return data;
              });
            } else {
              return new Promise<TroubleListItem>((resolve) => {
                resolve({troubleId: 0});
              });
            }
          }}
          params={{...currentRow}}
        >
          <ProFormText hidden name="troubleId"/>
          <ProFormSelect
            name="postId"
            label={'责任岗位'}
            rules={[{required: true}]}
            request={requestPost}
            disabled={editMode && !checkMode}
            fieldProps={{
              placeholder: '请选择责任岗位',
              dropdownMatchSelectWidth: false,
            }}
          />
          <ProFormTreeSelect
            name="orgId"
            label={'责任部门'}
            request={requestOrg}
            tooltip={'责任部门可以限定到部门对应的的岗位'}
            disabled={editMode && !checkMode}
            fieldProps={{
              allowClear: true,
              placeholder: '请选择部门',
              treeDefaultExpandAll: true,
              treeLine: true,
              fieldNames: {label: 'label', value: 'id', children: 'children'},
            }}
          />
          <ProFormDependency name={['postId', 'orgId']}>
            {({postId, orgId}) => {
              if (postId || orgId) {
                return (
                  <ProFormSelect
                    name="employeeId"
                    label={'责任人'}
                    tooltip={'可以将隐患限定到对应的人员'}
                    request={requestEmployee}
                    disabled={editMode && !checkMode}
                    params={{postId, orgId}}
                    fieldProps={{
                      placeholder: '请选择责任岗位',
                      dropdownMatchSelectWidth: false,
                    }}
                  />
                );
              }
              return null;
            }}
          </ProFormDependency>
          <ProFormText rules={[{required: true}]} label={'作业位置场所'} name="place"/>
          <ProFormSelect
            rules={[{required: true}]}
            label={'隐患源类型'}
            name="sourceType"
            valueEnum={sourceTypeData}
          />
          <ProFormTextArea rules={[{required: true}]} label={'隐患内容'} name="source"/>
          <ProFormTextArea rules={[{required: true}]} label={'排查方式'} name="checkMode"/>
          <ProFormSelect
            rules={[{required: true}]}
            label={'隐患级别'}
            name="level"
            fieldProps={{
              optionLabelProp: 'children',
              optionItemRender(item) {
                return <span style={{color: troubleColor[item.value]}}>{item.label}</span>;
              },
            }}
            valueEnum={troubleLevelData}
          />
          <ProFormSelect
            rules={[{required: true}]}
            label={'整改建议'}
            name="proposal"
            valueEnum={proposalData}
          />
          <ProFormTextArea rules={[{required: true}]} label={'整改措施'} name="measure"/>
          <ProFormSelect
            rules={[{required: true}]}
            label={'排查频次'}
            name="frequency"
            valueEnum={frequencyData}
            disabled={editMode && !checkMode}
          />
          <ProFormSelect
            name="handlerPost"
            label={'整改责任人岗位'}
            rules={[{required: true}]}
            request={requestPost}
            fieldProps={{
              placeholder: '请选择整改责任人岗位',
              dropdownMatchSelectWidth: false,
            }}
          />
          <ProFormDependency name={['handlerPost']}>
            {({handlerPost}) => {
              if (handlerPost)
                return (
                  <ProFormSelect
                    name="handler"
                    label={'整改责任人'}
                    rules={[{required: true}]}
                    request={requestEmployee}
                    params={{postId: handlerPost}}
                    fieldProps={{
                      placeholder: '请选择责任岗位',
                      dropdownMatchSelectWidth: false,
                    }}
                  />
                );
              return null;
            }}
          </ProFormDependency>
          <ProFormSelect
            name="verifierPost"
            label={'验收责任人岗位'}
            rules={[{required: true}]}
            request={requestPost}
            fieldProps={{
              placeholder: '请选择验收责任人岗位',
              dropdownMatchSelectWidth: false,
            }}
          />
          <ProFormDependency name={['verifierPost']}>
            {({verifierPost}) => {
              if (verifierPost)
                return (
                  <ProFormSelect
                    name="verifier"
                    label={'验收责任人'}
                    rules={[{required: true}]}
                    request={requestEmployee}
                    params={{postId: verifierPost}}
                    fieldProps={{
                      placeholder: '请选择验收责任人岗位',
                      dropdownMatchSelectWidth: false,
                    }}
                  />
                );

              return null;
            }}
          </ProFormDependency>
          <ProFormDependency name={['status']}>
            {({status}) => {
              if (status == '0')
                return (
                  <ProFormSelect
                    rules={[{required: true}]}
                    label={'状态'}
                    name="status"
                    valueEnum={{
                      0: {
                        text: '启用',
                        status: 'Success',
                      },
                      1: {
                        text: '禁用',
                        status: 'Error',
                      },
                    }}
                  />
                );

              return;
              <ProFormSelect
                rules={[{required: true}]}
                label={'状态'}
                name="status"
                valueEnum={{
                  1: {
                    text: '启用',
                    status: 'Success',
                  },
                  2: {
                    text: '禁用',
                    status: 'Error',
                  },
                }}
              />;
            }}
          </ProFormDependency>
        </ModalForm>

        <Drawer
          width={800}
          visible={showDetail}
          onClose={() => {
            setCurrentRow(undefined);
            setShowDetail(false);
          }}
          closable={false}
        >
          {currentRow?.place && (
            <ProDescriptions<TroubleListItem>
              column={1}
              bordered={true}
              title={currentRow?.place}
              request={getTrouble}
              layout={'horizontal'}
              params={currentRow}
              columns={columns as ProDescriptionsItemProps<TroubleListItem>[]}
            />
          )}
        </Drawer>
      </PageContainer>
    </CheckModule>
  );
};

export default TroublePage;
